package com.jxy.bean.constant;

import com.jxy.bean.ClassFile;
import com.jxy.tool.Tool;

import java.io.DataInputStream;

public class FieldrefInfo extends ConstantPool {
    public int class_index;
    public int name_and_type_index;

    public FieldrefInfo(DataInputStream dis, ClassFile cf) {
        super(ConstantPoolTag.CONSTANT_Fieldref.getTag(), cf);
        //长度u2
        class_index = Tool.readU2(dis);
        name_and_type_index = Tool.readU2(dis);
    }

    public String getClassName() {
        if (valid()) {
            ClassInfo classInfo = (ClassInfo)cf.getPools()[class_index];
            return classInfo.getClassName();
        }
        return "class_index err !";
    }

    public String getNameAndType() {
        if (valid()) {
            NameAndTypeInfo nameAndTypeInfo = (NameAndTypeInfo)cf.getPools()[name_and_type_index];
            return nameAndTypeInfo.getName() + " " + nameAndTypeInfo.getDescriptor();
        }
        return "name_and_type_index err !";
    }

    @Override
    public String toString() {
        return ConstantPoolTag.CONSTANT_Fieldref.getType() + "{tag:" + getTag() + ", class_index:" + class_index + "(" + getClassName() + "), name_and_type_index:" + name_and_type_index + "(" + getNameAndType() + ")}";
    }

    @Override
    public boolean valid() {
        //class_index必须指向CONSTANT_Class_info结构
        if (cf.getPools()[class_index].getTag() == ConstantPoolTag.CONSTANT_Class.getTag()) {
            //name_and_type_index必须指向CONSTANT_NameAndType结构
            if (cf.getPools()[name_and_type_index].getTag() == ConstantPoolTag.CONSTANT_NameAndType.getTag()) {
                return true;
            }
        }
        return false;
    }
}
